﻿using HalconDotNet;
using MotionControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using XXTUserUI;

namespace MainFrame
{
    public partial class PageConfig : Form
    {
        public PageConfig()
        {
            InitializeComponent();
        }
        bool IsFirst = true;
        private List<Button> lst_btn = new List<Button>();
        //public frm_Main frmAxisConfig;
        private void PageConfig_Load(object sender, EventArgs e)
        {
            if (GlobalVar.userConfig == null)
                GlobalVar.userConfig = new ConfigData();
            PameraToControl();
            this.rbn_plate1.CheckedChanged += new System.EventHandler(this.rbn_ScanCamera_CheckedChanged);
            rbn_ScanCamera_CheckedChanged(rbn_plate1, null);

            //20241207修改更换海康相机屏蔽现有相机连接
            //Task.Run(()=>
            //{
            //    ConnectCamera();
            //});

            hswc_Postion.HalconWindow.SetDraw("margin");
            hswc_Postion.SetFullImagePart();
            visionProc.UpdataImage += DispObject;
            if (IsFirst)
            {
                IsFirst = false;
                GlobalVar.frmAxisConfig = new frm_Main();
                GlobalVar.frmAxisConfig.TopLevel = false;
                GlobalVar.frmAxisConfig.FormBorderStyle = FormBorderStyle.None;
                GlobalVar.frmAxisConfig.Parent = pl_motor;
                GlobalVar.frmAxisConfig.Dock = DockStyle.Fill;
                GlobalVar.frmAxisConfig.Show();
                tabControl1.SelectedTab = tpg_Moter;

                var plcList = new ContextMenuStrip();
                var zoomAdd = new ToolStripMenuItem("新增行");
                zoomAdd.Click += new System.EventHandler(this.dv_addRow_Click);
                plcList.Items.Add(zoomAdd);
                var zoomDelete = new ToolStripMenuItem("删除选中行");
                zoomDelete.Click += new System.EventHandler(this.dv_DeleteRow_Click);
                plcList.Items.Add(zoomDelete);
                dgv_camera_calib.ContextMenuStrip = plcList;

                var cmdList = new ContextMenuStrip();
                var cmdAdd = new ToolStripMenuItem("新增行");
                cmdAdd.Click += new System.EventHandler(this.cmd_addRow_Click);
                cmdList.Items.Add(cmdAdd);
                var cmdDelete = new ToolStripMenuItem("删除选中行");
                cmdDelete.Click += new System.EventHandler(this.cmd_DeleteRow_Click);
                cmdList.Items.Add(cmdDelete);

                dgv_cmd.ContextMenuStrip = cmdList;
                Task.Run(()=>
                {
                    try
                    {
                        uTCPIP2.tcpInit();
                        if (uTCPIP2.isInitOk)
                            GlobalVar.mesTcp = new MesTCP(uTCPIP2.m_socketHelper);
                    }
                    catch (Exception)
                    {

                    }
                });
                
                //连接海康视觉
                Task.Run(() =>
                {
                    try
                    {
                        GlobalVar.VisionTcpIP.Link("127.0.0.1", 8000);
                    }
                    catch (Exception)
                    {

                    }
                });

                Task.Factory.StartNew(new Action(() =>
                {
                    var lockTemp = new object();
                    var ntcp = 0;
                    while (!GlobalVar.isExit)
                    {
                        System.Threading.Thread.Sleep(50);
                        if (GlobalVar.mesTcp==null)
                        {
                            continue;
                        }
                        if (GlobalVar.userConfig.UploadInfo.IsUploadTcp)
                        {
                            if (ntcp > 1)
                                return;
                            if (GlobalVar.mesTcp.m_socket.tcp_client_connect)
                            {
                                GlobalVar.IsMesTCPOK = true;
                                break;
                            }
                            else
                            {
                                Application.DoEvents();
                                Thread.Sleep(9000);
                                ntcp++;
                                this.BeginInvoke(new Action(() =>
                                {
                                    lock (lockTemp)
                                    {
                                        uTCPIP2.tcpInit();
                                        if (uTCPIP2.isInitOk)
                                            GlobalVar.mesTcp = new MesTCP(uTCPIP2.m_socketHelper);
                                    }
                                }));
                            }
                        }
                        else
                            break;
                    }
                }));
                try
                {
                    if (!GlobalVar.userConfig.RFIDBox.IsEnableRFID)
                    {
                        uSerialPort1.Init();
                        GlobalVar.Box1 = new BoxPort(uSerialPort1.spHelper.m_sp);
                        GlobalVar.Box1.displayInfoMain += displalyInfo.displayInfoMainBox;
                        Application.DoEvents();
                        Thread.Sleep(100);
                        Application.DoEvents();
                        uSerialPort2.Init();
                        GlobalVar.Box2 = new BoxPort(uSerialPort2.spHelper.m_sp);
                        GlobalVar.Box2.displayInfoMain += displalyInfo.displayInfoMainBox;
                    }
                    else
                    {
                        GlobalVar.RFIDBox_in = new RFIDDLL.RFIDbox() { boxIndex = 0, com = GlobalVar.userConfig.RFIDBox.in_COM, Bandrate = GlobalVar.userConfig.RFIDBox.in_Baudrate };
                        GlobalVar.RFIDBox_in.connectRFID();
                        GlobalVar.RFIDBox_out = new RFIDDLL.RFIDbox() { boxIndex = 1, com = GlobalVar.userConfig.RFIDBox.out_COM, Bandrate = GlobalVar.userConfig.RFIDBox.out_Baudrate };
                        GlobalVar.RFIDBox_out.connectRFID();
                    }
                }
                catch
                {

                }
            }
        }

        public void DispObject(HObject drawObject, string color="green")
        {
            try
            {
                if (InvokeRequired)
                {
                    hswc_Postion.Invoke(new MethodInvoker(() =>
                    {
                        hswc_Postion.SetFullImagePart();
                        hswc_Postion.HalconWindow.ClearWindow();
                        hswc_Postion.HalconWindow.SetColor(color);
                        hswc_Postion.HalconWindow.SetDraw("margin");
                        hswc_Postion.HalconWindow.DispObj(drawObject);
                    }));
                }
                else
                {
                    hswc_Postion.SetFullImagePart();
                    hswc_Postion.HalconWindow.ClearWindow();
                    hswc_Postion.HalconWindow.DispObj(visionProc.srcObject_pos);
                    hswc_Postion.HalconWindow.SetColor(color);
                    hswc_Postion.HalconWindow.SetDraw("margin");
                    hswc_Postion.HalconWindow.DispObj(drawObject);

                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("定位相机检测显示异常:" + ex.Message);

            }
        }
        public void DispObject(HObject drawObject)
        {
            try
            {
                string color = "green";
                if (InvokeRequired)
                {
                    hswc_Postion.Invoke(new MethodInvoker(() =>
                    {
                        hswc_Postion.SetFullImagePart();
                        hswc_Postion.HalconWindow.ClearWindow();
                        hswc_Postion.HalconWindow.SetColor(color);
                        hswc_Postion.HalconWindow.SetDraw("margin");
                        hswc_Postion.HalconWindow.DispObj(drawObject);
                    }));
                }
                else
                {
                    hswc_Postion.SetFullImagePart();
                    hswc_Postion.HalconWindow.ClearWindow();
                    hswc_Postion.HalconWindow.DispObj(visionProc.srcObject_pos);
                    hswc_Postion.HalconWindow.SetColor(color);
                    hswc_Postion.HalconWindow.SetDraw("margin");
                    hswc_Postion.HalconWindow.DispObj(drawObject);

                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("定位相机检测显示异常:" + ex.Message);

            }
        }

        private void rbn_ScanCamera_CheckedChanged(object sender, EventArgs e)
        {
            var e_cur = GetPosCamera();
            var curVision = GlobalVar.userConfig.PlateVisionList[(int)e_cur];
            if (curVision.CailList != null)
                CailPointToTable(curVision.CailList);
            nud_CenterXplate.Value = (decimal)curVision.CenterRealX;
            nud_CenterYplate.Value = (decimal)curVision.CenterRealY;
        }
        private void ConnectCamera()
        {
            HikVision cam = new HikVision(GlobalVar.userConfig.CameraSN_pos);
            if (cam.isInitSuccess)
            {
                cam.SetTriggerMode(TriggerMode.softTrigger);
                cam.StartGrab();
                cam.imageOut += visionProc.cam1;
                displalyInfo.displayInfoMain("定位相机连接成功");
            }
            GlobalVar.cameraList.Add(cam);
            HikVision camdraw = new HikVision(GlobalVar.userConfig.CameraSN_draw);
            if (camdraw.isInitSuccess)
            {
                camdraw.SetTriggerMode(TriggerMode.softTrigger);
                camdraw.StartGrab();
                camdraw.imageOut += visionProc.cam2;
                displalyInfo.displayInfoMain("图案相机连接成功");

            }
            GlobalVar.cameraList.Add(camdraw);
            HikVision cam_check = new HikVision(GlobalVar.userConfig.CameraSN_check);
            if (cam_check.isInitSuccess)
            {
                cam_check.SetTriggerMode(TriggerMode.softTrigger);
                cam_check.StartGrab();
                cam_check.imageOut += visionProc.cam3;
                displalyInfo.displayInfoMain("检测相机连接成功");
            }
            GlobalVar.cameraList.Add(cam_check);
        }
        private void dv_addRow_Click(object sender, EventArgs e)
        {
            dgv_camera_calib.Rows.Add(new object[9] { dgv_camera_calib.Rows.Count + 1, 0, 0, 0, 0, 0,"移动","读取","读取" });
        }
        private void dv_DeleteRow_Click(object sender, EventArgs e)
        {
            if (dgv_camera_calib.SelectedRows.Count > 0)
            {
                if (DialogResult.Yes == MessageBox.Show("确定要删除选中行？", "询问", MessageBoxButtons.YesNo))
                    dgv_camera_calib.Rows.Remove(dgv_camera_calib.SelectedRows[0]);
            }

        }
        private void cmd_addRow_Click(object sender, EventArgs e)
        {
            dgv_cmd.Rows.Add(new object[2] { dgvc_action.Items[0].ToString(), "@|" });
        }
        private void cmd_DeleteRow_Click(object sender, EventArgs e)
        {
            if (dgv_cmd.SelectedRows.Count > 0)
            {
                if (DialogResult.Yes == MessageBox.Show("确定要删除选中行？", "询问", MessageBoxButtons.YesNo))
                    dgv_cmd.Rows.Remove(dgv_cmd.SelectedRows[0]);
            }

        }
        private void CailPointToTable(List<CalibPoint> lst)
        {
            this.Invoke(new Action(() => {
                dgv_camera_calib.Rows.Clear();
                if (lst != null)
                {
                    lst.OrderBy(a => a.Index).ToList().ForEach(a =>
                    {
                        dgv_camera_calib.Rows.Add(new object[9] { a.Index, a.pixX, a.pixY, a.realX, a.realY, a.realR,"移动","读取轴坐标", "读取像素" });
                    });
                }
            }));

        }
        /// <summary>
        /// 将配置显示到控件上
        /// </summary>
        private void PameraToControl()
        {
            #region 上层输送模块

            ckb_IsEnableUpSignal.Checked = GlobalVar.userConfig.isEnableUpSignal;
            ckb_IsEnableDownSignal.Checked = GlobalVar.userConfig.isEnableDownSignal;
            nud_NG_distance.Value = (decimal)GlobalVar.userConfig.NG_distance;
            nud_dis_ConveryReset.Value = (decimal)GlobalVar.userConfig.dis_ConveryReset;
            nud_DownCheckProIn.Value = GlobalVar.userConfig.downProTime_In;
            nud_DownCheckProOut.Value = GlobalVar.userConfig.downProTime_out;
            nud_DownAlarmOut.Value = GlobalVar.userConfig.downAlarmOut;
            nud_DownDeleyArivel.Value = GlobalVar.userConfig.downDelayArivel;
            nud_DownDelayCheck.Value = GlobalVar.userConfig.DelayCheck_Down;
            nud_DownAutoTime.Value = GlobalVar.userConfig.downAutoTime;
            nud_downDelayBlock.Value = GlobalVar.userConfig.downDelayBlock;
            #endregion
            #region 相机模块

            rbn_plate1.Checked = true;
            rbn_plate2.Checked = false;
            if (GlobalVar.userConfig.PlateVisionList == null)
            {
                GlobalVar.userConfig.PlateVisionList = new List<PlateVisionInfo>();
                plateCount = Enum.GetNames(typeof(e_CameraPlate)).Length;
                for (int i = 0; i < plateCount; i++)
                {
                    GlobalVar.userConfig.PlateVisionList.Add(new PlateVisionInfo());
                }
            }
            var curPlate = GetPosCamera();
            tbx_CameraSn_Pos.Text = GlobalVar.userConfig.CameraSN_pos;
            tbx_CameraSn_Draw.Text = GlobalVar.userConfig.CameraSN_draw;
            tbx_CameraSn_Check.Text = GlobalVar.userConfig.CameraSN_check;
            if (GlobalVar.userConfig.PlateVisionList[(int)curPlate].CailList != null)
            {
                CailPointToTable(GlobalVar.userConfig.PlateVisionList[(int)curPlate].CailList);
            }
            nud_delayCamera.Value = GlobalVar.userConfig.delayCamera;
            nud_cameraNGTimes.Value = GlobalVar.userConfig.CameraNGTime;
            nud_getLabelNGTimes.Value = GlobalVar.userConfig.getLabelNGTimes;
            #endregion
            #region 数据库操作
            tbx_db_IP.Text = GlobalVar.userConfig.db_IP;
            tbx_db_UserName.Text = GlobalVar.userConfig.db_UserName;
            tbx_db_Name.Text = GlobalVar.userConfig.db_Name;
            tbx_db_Password.Text = GlobalVar.userConfig.db_Password;
            tbx_db_T_AlarmInfo.Text = GlobalVar.userConfig.db_T_Alarm;
            tbx_db_T_Product.Text = GlobalVar.userConfig.db_T_Product;
            tbx_db_T_MachineStatus.Text = GlobalVar.userConfig.db_T_Status;
            #endregion
            ckb_IsCutFinishOK.Checked = GlobalVar.userConfig.isCutFinishOK;
            nud_airCutTime.Value = GlobalVar.userConfig.airCutTime;
            nud_LabelKeepAirTime.Value = GlobalVar.userConfig.LabelKeepAirTime;
            nud_cutKeepTime.Value = GlobalVar.userConfig.CutKeepTime;
            nud_DelayNGair.Value = GlobalVar.userConfig.deleyNGair;
            nud_ConveryOpen_time.Value = GlobalVar.userConfig.ConveryOpen_time;
            nud_ConveryReset_time.Value = GlobalVar.userConfig.ConveryReset_time;

            nud_delayBlock1.Value = GlobalVar.userConfig.delayBlock1;
            TimeOut_In.Value = GlobalVar.userConfig.TimeOut_In;
            nud_delayLift2.Value = GlobalVar.userConfig.delayLift2;
            nud_delayBlock2.Value = GlobalVar.userConfig.delayBlock2;
            nud_Leave1TimeOut.Value = GlobalVar.userConfig.TimeOut_Leave1;
            IgnoreFrontSignal.Checked = GlobalVar.userConfig.IgnoreFrontSignal;
            #region 贴标模块
            ckb_MaualScan.Checked = GlobalVar.userConfig.isEnableVisionsyr;
            ckb_IsAutoFly.Checked = GlobalVar.userConfig.IsAutoFly;
            nud_ClampTime.Value = GlobalVar.userConfig.clampTime;
            nud_airTime.Value = GlobalVar.userConfig.airTime;
            nud_flyLabelNGTimes.Value = GlobalVar.userConfig.getFlyNGTimes;
            nud_WrodAlarm.Value = GlobalVar.userConfig.WrodAlarm;
            num_NoLabel.Value = GlobalVar.userConfig.NoLabel;
            ckb_PickCheck.Checked = GlobalVar.userConfig.PickCheck;

            ckb_IsPosOk.Checked = GlobalVar.userConfig.isPosOk;
            ckb_IsWordOk.Checked = GlobalVar.userConfig.IsWordOk;
            ckb_IsLabelResultOk.Checked = GlobalVar.userConfig.IsLabelResultOk;
            ckb_IsGetLabelTwo.Checked = GlobalVar.userConfig.IsGetLabelTwo;

            ckb_IsGetLabelOK.Checked = GlobalVar.userConfig.IsGetLabelOK;

            nud_airRepeatTime.Value = GlobalVar.userConfig.airRepeatTime;
            nud_airIntervel.Value = GlobalVar.userConfig.airInterval;

            ckb_IsLabelFinishOK.Checked = GlobalVar.userConfig.isLabelFinishOK;
            ckb_IsPosAfterLabel.Checked = GlobalVar.userConfig.IsPosAfterLabel;
            ckb_IsCheckCutResult.Checked = GlobalVar.userConfig.IsCheckCutResult;
            nud_deleyNGrotate.Value = GlobalVar.userConfig.deleyNGRotate;
            nud_deleyNGup.Value = GlobalVar.userConfig.deleyNGup;
            nud_getLabelNGTimes_auto.Value = GlobalVar.userConfig.getLabelNGTimes_auto;
            #endregion

            #region 数据上传
            if (GlobalVar.userConfig.UploadInfo == null)
                GlobalVar.userConfig.UploadInfo = new UrlInfo();
            tbx_DevCode.Text = GlobalVar.userConfig.UploadInfo.DevCode;
            ckb_EnableTcp.Checked = GlobalVar.userConfig.UploadInfo.IsUploadTcp;
            ckb_EnableUrl.Checked = GlobalVar.userConfig.UploadInfo.IsUploadUrl;
            tbx_url_Alarm.Text = GlobalVar.userConfig.UploadInfo.url_AlarmUpload;
            tbx_url_Check.Text = GlobalVar.userConfig.UploadInfo.url_CheckUpload;
            tbx_url_Data.Text = GlobalVar.userConfig.UploadInfo.url_DataUpload;
            tbx_url_GetDate.Text = GlobalVar.userConfig.UploadInfo.url_GetDate;
            tbx_url_GetModelInfo.Text = GlobalVar.userConfig.UploadInfo.url_GetModelInfo;
            tbx_url_DevStatusHead.Text = GlobalVar.userConfig.UploadInfo.url_DevStatusHead;
            tbx_DeviceName.Text = GlobalVar.userConfig.UploadInfo.url_DeviceName;
            if (GlobalVar.userConfig.cmdList == null)
            {
                GlobalVar.userConfig.cmdList = new List<Cmd>();
            }
            CmdListToTable(GlobalVar.userConfig.cmdList);
            #endregion
            #region 读卡器
            if (GlobalVar.userConfig.RFIDBox == null)
                GlobalVar.userConfig.RFIDBox = new Box_RFID();
            tbx_r_NGflag.Text = GlobalVar.userConfig.RFIDBox.NGflag;
            tbx_r_NGNG.Text = GlobalVar.userConfig.RFIDBox.NGNG;
            tbx_r_NGOK.Text = GlobalVar.userConfig.RFIDBox.NGOK;
            tbx_r_RM.Text = GlobalVar.userConfig.RFIDBox.MR;
            tbx_r_RMAuto.Text = GlobalVar.userConfig.RFIDBox.MR_Auto;
            nud_r_nReadtimes.Value = GlobalVar.userConfig.RFIDBox.nReadTimes;
            nud_nWriteTimes.Value = GlobalVar.userConfig.RFIDBox.nWriteTimes;
            tbx_r_OK.Text = GlobalVar.userConfig.RFIDBox.OK;
            tbx_r_Station.Text = GlobalVar.userConfig.RFIDBox.station;
            ckb_IsEnableRFID.Checked = GlobalVar.userConfig.RFIDBox.IsEnableRFID;
            ckb_IsEnableWR.Checked = GlobalVar.userConfig.RFIDBox.IsEnable;
            tbx_in_Com.Text = GlobalVar.userConfig.RFIDBox.in_COM;
            tbx_out_Com.Text = GlobalVar.userConfig.RFIDBox.out_COM;
            nud_in_Baudrate.Value = GlobalVar.userConfig.RFIDBox.in_Baudrate;
            nud_out_BaudRate.Value = GlobalVar.userConfig.RFIDBox.out_Baudrate;
            #endregion


            numericUpDown1.Value = (decimal)GlobalVar.userConfig.CalibrationXY;
            numericUpDown2.Value = (decimal)GlobalVar.userConfig.CalibrationAngle;

        }
        private void CmdListToTable(List<Cmd> lst)
        {
            dgv_cmd.Rows.Clear();
            if (lst != null)
            {
                lst.ToList().ForEach(a =>
                {
                    dgv_cmd.Rows.Add(new object[2] { a.action, a.cmd });
                });
            }
        }
      

      
        private int plateCount = 2;
        private void btn_SaveConfig_Click(object sender, EventArgs e)
        {
            if (GlobalVar.userConfig == null)
                GlobalVar.userConfig = new ConfigData();

            #region 上层输送模块

            GlobalVar.userConfig.isEnableUpSignal = ckb_IsEnableUpSignal.Checked;
            GlobalVar.userConfig.isEnableDownSignal = ckb_IsEnableDownSignal.Checked;
            GlobalVar.userConfig.NG_distance = (double)nud_NG_distance.Value;
            GlobalVar.userConfig.dis_ConveryReset = (int)nud_dis_ConveryReset.Value;
            #endregion

            #region 相机模块
            GlobalVar.userConfig.CameraSN_pos = tbx_CameraSn_Pos.Text;
            GlobalVar.userConfig.CameraSN_draw = tbx_CameraSn_Draw.Text;
           GlobalVar.userConfig.CameraSN_check = tbx_CameraSn_Check.Text;
            plateCount = Enum.GetNames(typeof(e_CameraPlate)).Length;
            if (GlobalVar.userConfig.PlateVisionList == null)
            {
                GlobalVar.userConfig.PlateVisionList = new List<PlateVisionInfo>();
                for (int i = 0; i < plateCount; i++)
                {
                    GlobalVar.userConfig.PlateVisionList.Add(new PlateVisionInfo());
                }
            }
            if (GlobalVar.userConfig.PlateVisionList.Count < plateCount)
            {
                for (int i = GlobalVar.userConfig.PlateVisionList.Count; i < plateCount; i++)
                {
                    GlobalVar.userConfig.PlateVisionList.Add(new PlateVisionInfo());
                }
            }
            var curPlat = GetPosCamera();

            GlobalVar.userConfig.PlateVisionList[(int)curPlat].CailList = GetCailPoint();
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].CenterRealX = (double)nud_CenterXplate.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].CenterRealY = (double)nud_CenterYplate.Value;
            GlobalVar.userConfig.delayCamera = (int)nud_delayCamera.Value;
            #endregion
            #region 数据库操作
            GlobalVar.userConfig.db_IP = tbx_db_IP.Text;
            GlobalVar.userConfig.db_UserName = tbx_db_UserName.Text;
            GlobalVar.userConfig.db_Name = tbx_db_Name.Text;
            GlobalVar.userConfig.db_Password = tbx_db_Password.Text;
            GlobalVar.userConfig.db_T_Alarm = tbx_db_T_AlarmInfo.Text;
            GlobalVar.userConfig.db_T_Product = tbx_db_T_Product.Text;
            GlobalVar.userConfig.db_T_Status = tbx_db_T_MachineStatus.Text;
            #endregion
            GlobalVar.userConfig.airCutTime = (int)nud_airCutTime.Value;
            GlobalVar.userConfig.DelayCheck_Down = (int)nud_DownDelayCheck.Value;
            GlobalVar.userConfig.isCutFinishOK = ckb_IsCutFinishOK.Checked;
            GlobalVar.userConfig.LabelKeepAirTime=(int)nud_LabelKeepAirTime.Value;
            GlobalVar.userConfig.CutKeepTime = (int)nud_cutKeepTime.Value;
            GlobalVar.userConfig.deleyNGair = (int)nud_DelayNGair.Value;
            GlobalVar.userConfig.downProTime_In = (int)nud_DownCheckProIn.Value;
            GlobalVar.userConfig.downProTime_out = (int)nud_DownCheckProOut.Value;
            GlobalVar.userConfig.downAlarmOut = (int)nud_DownAlarmOut.Value;
            GlobalVar.userConfig.downDelayArivel = (int)nud_DownDeleyArivel.Value;
            GlobalVar.userConfig.downAutoTime = (int)nud_DownAutoTime.Value;
            GlobalVar.userConfig.downDelayBlock = (int)nud_downDelayBlock.Value;
            GlobalVar.userConfig.ConveryOpen_time = (int)nud_ConveryOpen_time.Value;
            GlobalVar.userConfig.ConveryReset_time = (int)nud_ConveryReset_time.Value;

            GlobalVar.userConfig.TimeOut_In = (int)TimeOut_In.Value;
            GlobalVar.userConfig.delayBlock1 = (int)nud_delayBlock1.Value;
            GlobalVar.userConfig.delayLift2 = (int)nud_delayLift2.Value;
            GlobalVar.userConfig.delayBlock2 = (int)nud_delayBlock2.Value;
            GlobalVar.userConfig.TimeOut_Leave1 = (int)nud_Leave1TimeOut.Value;
            GlobalVar.userConfig.IgnoreFrontSignal = IgnoreFrontSignal.Checked;
            #region 贴标模块
            GlobalVar.userConfig.IsAutoFly = ckb_IsAutoFly.Checked;
            GlobalVar.userConfig.isEnableVisionsyr = ckb_MaualScan.Checked;
   
            GlobalVar.userConfig.clampTime = (int)nud_ClampTime.Value;
            GlobalVar.userConfig.airTime = (int)nud_airTime.Value;
            GlobalVar.userConfig.IsLabelResultOk = ckb_IsLabelResultOk.Checked;
            GlobalVar.userConfig.IsWordOk = ckb_IsWordOk.Checked;
            GlobalVar.userConfig.isPosOk = ckb_IsPosOk.Checked;
            GlobalVar.userConfig.IsGetLabelTwo = ckb_IsGetLabelTwo.Checked;
            GlobalVar.userConfig.CameraNGTime = (int)nud_cameraNGTimes.Value;
            GlobalVar.userConfig.getLabelNGTimes = (int)nud_getLabelNGTimes.Value;
            GlobalVar.userConfig.getFlyNGTimes = (int)nud_flyLabelNGTimes.Value;
            GlobalVar.userConfig.WrodAlarm = (int)nud_WrodAlarm.Value; 
                GlobalVar.userConfig.NoLabel = (int)num_NoLabel.Value;
            GlobalVar.userConfig.PickCheck = ckb_PickCheck.Checked; 
            GlobalVar.userConfig.IsGetLabelOK = ckb_IsGetLabelOK.Checked;
            GlobalVar.userConfig.airRepeatTime = (int)nud_airRepeatTime.Value;
            GlobalVar.userConfig.airInterval = (int)nud_airIntervel.Value;
            

            GlobalVar.userConfig.isLabelFinishOK = ckb_IsLabelFinishOK.Checked;
            GlobalVar.userConfig.IsPosAfterLabel = ckb_IsPosAfterLabel.Checked;
            GlobalVar.userConfig.IsCheckCutResult = ckb_IsCheckCutResult.Checked;
            GlobalVar.userConfig.deleyNGRotate = (int)nud_deleyNGrotate.Value;
            GlobalVar.userConfig.deleyNGup = (int)nud_deleyNGup.Value;
            GlobalVar.userConfig.getLabelNGTimes_auto = (int)nud_getLabelNGTimes_auto.Value;
            #endregion
            #region 数据上传
            if (GlobalVar.userConfig.UploadInfo == null)
                GlobalVar.userConfig.UploadInfo = new UrlInfo();
            GlobalVar.userConfig.UploadInfo.DevCode = tbx_DevCode.Text.Trim();
            GlobalVar.userConfig.UploadInfo.IsUploadTcp = ckb_EnableTcp.Checked;
            GlobalVar.userConfig.UploadInfo.IsUploadUrl = ckb_EnableUrl.Checked;
            GlobalVar.userConfig.UploadInfo.url_AlarmUpload = tbx_url_Alarm.Text;
            GlobalVar.userConfig.UploadInfo.url_CheckUpload = tbx_url_Check.Text;
            GlobalVar.userConfig.UploadInfo.url_DataUpload = tbx_url_Data.Text;
            GlobalVar.userConfig.UploadInfo.url_GetDate = tbx_url_GetDate.Text;
            GlobalVar.userConfig.UploadInfo.url_GetModelInfo = tbx_url_GetModelInfo.Text;
            GlobalVar.userConfig.UploadInfo.url_DevStatusHead = tbx_url_DevStatusHead.Text;
            GlobalVar.userConfig.UploadInfo.url_DeviceName = tbx_DeviceName.Text;

            GlobalVar.userConfig.cmdList = GetCmdList();
            uTCPIP2.SaveParameter();
          
            #endregion
            #region 读卡器
            if (GlobalVar.userConfig.RFIDBox == null)
                GlobalVar.userConfig.RFIDBox = new Box_RFID();
            GlobalVar.userConfig.RFIDBox.NGflag = tbx_r_NGflag.Text;
            GlobalVar.userConfig.RFIDBox.NGNG = tbx_r_NGNG.Text;
            GlobalVar.userConfig.RFIDBox.NGOK = tbx_r_NGOK.Text;
            GlobalVar.userConfig.RFIDBox.MR = tbx_r_RM.Text;
            GlobalVar.userConfig.RFIDBox.MR_Auto = tbx_r_RMAuto.Text;
            GlobalVar.userConfig.RFIDBox.nReadTimes = (int)nud_r_nReadtimes.Value;
            GlobalVar.userConfig.RFIDBox.nWriteTimes = (int)nud_nWriteTimes.Value;
            GlobalVar.userConfig.RFIDBox.OK = tbx_r_OK.Text;
            GlobalVar.userConfig.RFIDBox.station = tbx_r_Station.Text;
            GlobalVar.userConfig.RFIDBox.IsEnableRFID = ckb_IsEnableRFID.Checked;
            GlobalVar.userConfig.RFIDBox.IsEnable = ckb_IsEnableWR.Checked;
            GlobalVar.userConfig.RFIDBox.in_COM = tbx_in_Com.Text;
            GlobalVar.userConfig.RFIDBox.out_COM = tbx_out_Com.Text;
            GlobalVar.userConfig.RFIDBox.in_Baudrate = (int)nud_in_Baudrate.Value;
            GlobalVar.userConfig.RFIDBox.out_Baudrate = (int)nud_out_BaudRate.Value;
            #endregion

            GlobalVar.userConfig.CalibrationXY = (double)numericUpDown1.Value;
            GlobalVar.userConfig.CalibrationAngle = (double)numericUpDown2.Value;

            GlobalVar.userConfig.LeftFitCompensationX =(double)LeftFitCompensationX.Value;
            GlobalVar.userConfig.LeftFitCompensationY = (double)LeftFitCompensationY.Value;
            GlobalVar.userConfig.LeftFitCompensationA = (double)LeftFitCompensationA.Value;

            GlobalVar.userConfig.RightFitCompensationX = (double)RightFitCompensationX.Value;
            GlobalVar.userConfig.RightFitCompensationY = (double)RightFitCompensationY.Value;
            GlobalVar.userConfig.RightFitCompensationA = (double)RightFitCompensationA.Value;


            if (!GlobalVar.userConfig.RFIDBox.IsEnableRFID)
            {
                uSerialPort1.SaveParameter();
                uSerialPort2.SaveParameter();
            }
            else
            {
                
            }
            SerializeHelper.serializeFile(GlobalVar.configPath, GlobalVar.userConfig, "软件配置");
        }
        private e_CameraPlate GetPosCamera()
        {
            if (rbn_plate1.Checked)
                return e_CameraPlate.定位相机平台1;
            if (rbn_plate2.Checked)
                return e_CameraPlate.定位相机平台2;
            else
                return e_CameraPlate.定位相机平台1;
        }
        private List<CalibPoint> GetCailPoint()
        {
            try
            {
                var CailList = new List<CalibPoint>();
                for (int i = 0; i < dgv_camera_calib.Rows.Count; i++)
                {
                    var curCailPoint = new CalibPoint();
                    curCailPoint.Index = Convert.ToInt32(dgv_camera_calib.Rows[i].Cells["dgvc_index"].Value);
                    curCailPoint.pixX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_pixX"].Value);
                    curCailPoint.pixY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_pixY"].Value);
                    curCailPoint.realX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_realX"].Value);
                    curCailPoint.realY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_realY"].Value);
                    curCailPoint.realR = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_realR"].Value);
                    CailList.Add(curCailPoint);
                }
                return CailList;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        private List<Cmd> GetCmdList()
        {
            try
            {
                var CailList = new List<Cmd>();
                for (int i = 0; i < dgv_cmd.Rows.Count; i++)
                {
                    var curCmd = new Cmd();
                    curCmd.action = Convert.ToString(dgv_cmd.Rows[i].Cells["dgvc_action"].Value);
                    curCmd.cmd = Convert.ToString(dgv_cmd.Rows[i].Cells["dgvc_msg"].Value);
                    CailList.Add(curCmd);
                }
                return CailList;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

        private void btn_calibrate_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgv_camera_calib.Rows == null || dgv_camera_calib.Rows.Count < 4)
                {
                    MessageBox.Show("标定数据太少，请准备至少9个点数据");
                    return;
                }
                if (DialogResult.No == MessageBox.Show($"确定要{((Button)sender).Text}吗?", "询问", MessageBoxButtons.YesNo))
                    return;

                    #region 取表格数据
                List<PointF> calibrate_RealPoint = new List<PointF>();
                List<PointF> calibrate_PixPoint = new List<PointF>();
                List<PointF> rotate_RealPoint = new List<PointF>();
                List<PointF> rotate_PixPoint = new List<PointF>();
                PointF actPoint = new PointF() { X = 0, Y = 0 };
                this.Invoke(new Action(() => {
                    for (int i = 0; i < dgv_camera_calib.Rows.Count; i++)
                    {
                        if (dgv_camera_calib.Rows[i].Cells[1].Value != null && dgv_camera_calib.Rows[i].Cells[2].Value != null)
                        {
                            var curX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[1].Value);
                            var curY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[2].Value);
                            if (i < 9)
                                calibrate_PixPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                            else
                                rotate_PixPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                        }
                    }
                    for (int i = 0; i < dgv_camera_calib.Rows.Count; i++)
                    {
                        if (dgv_camera_calib.Rows[i].Cells[3].Value != null && dgv_camera_calib.Rows[i].Cells[4].Value != null)
                        {
                            var curX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[3].Value);
                            var curY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[4].Value);
                            if (i < 9)
                                calibrate_RealPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                            else
                            {
                                rotate_RealPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                                actPoint = new PointF()
                                {
                                    X = Convert.ToSingle(curX),
                                    Y = Convert.ToSingle(curY)
                                };
                            }
                        }
                    }
                    #endregion

                }));
                var curCamera = GetPosCamera();

                #region 九点标定+旋转标定
                var caildata = visionProc.CalibratePlate(calibrate_PixPoint, calibrate_RealPoint);
                if (caildata != null && caildata.Type != HTupleType.EMPTY && caildata.DArr.Length > 0)
                {
                    var tempCail = caildata;
                    var cailpixdata = visionProc.CalibratePlate(calibrate_RealPoint, calibrate_PixPoint);

                    HOperatorSet.HomMat2dToAffinePar(tempCail, out HTuple sx, out HTuple sy, out HTuple phi, out HTuple theta, out HTuple tx, out HTuple ty);
                    displalyInfo.displayInfoMain(JsonConvert.SerializeObject(caildata.DArr) + $"sx{sx.D}" + $"sy{sy.D}" + $"phi{phi.D}" + $"theta{theta.D}" + $"tx{tx.D}" + $"ty{ty.D}");
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].arr_cail = caildata.DArr;
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].arr_pixcail = cailpixdata.DArr;
                    var Point_realRorate = visionProc.CalibrateRotateCenter(GlobalVar.userConfig.PlateVisionList[(int)curCamera].arr_cail, rotate_PixPoint, actPoint);
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealX = Point_realRorate.X;
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealY = Point_realRorate.Y;
                    if (rotate_RealPoint.Count > 0)
                    {
                        GlobalVar.userConfig.PlateVisionList[(int)curCamera].CailPointX = rotate_RealPoint[0].X;
                        GlobalVar.userConfig.PlateVisionList[(int)curCamera].CailPointY = rotate_RealPoint[0].Y;
                    }
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].rorateOffsetX = (double)visionProc.RorateOffset.X;
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].rorateOffsetY = (double)visionProc.RorateOffset.Y;
                    this.Invoke(new Action(() => {
                        nud_CenterXplate.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealX;
                        nud_CenterYplate.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealY;
                    }));
                 
                    #endregion
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        private async void btn_Cail_Click(object sender, EventArgs e)
        {
            if (dgv_camera_calib.Rows == null || dgv_camera_calib.Rows.Count < 4)
            {
                MessageBox.Show("标定数据太少，请准备至少9个点数据");
                return;
            }
            if (DialogResult.No == MessageBox.Show($"确定要{((Button)sender).Text}吗?", "询问", MessageBoxButtons.YesNo))
                return;
            ((Button)sender).Enabled = false;

            await Task.Run(new Action(() => 
            {
                var curSelect = GetPosCamera();
                var curVision = GlobalVar.userConfig.PlateVisionList[(int)curSelect];
                switch (curSelect)
                {
                    case e_CameraPlate.定位相机平台1:
                        if (curVision.CailList != null && curVision.CailList.Count >= 9)
                        {
                            var temp_cailArr = curVision.CailList.ToArray();
                            var isMoveOK = false;
                            visionProc.curCameraPlate1 = curSelect;
                            isMoveOK = GlobalMotion.toPosition(-100, (int)e_card1_axis.贴标X2上, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;

                            for (int i = 0; i < temp_cailArr.Length; i++)
                            {
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realX, (int)e_card1_axis.贴标X1下, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realY, (int)e_card1_axis.贴标Y轴, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realR, (int)e_card1_axis.贴标R1下, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                visionProc.Result1 = null;
                                GlobalVar.e_Camera_Pos1 = e_Camera_Pos.未拍照;
                                Thread.Sleep(GlobalVar.userConfig.delayCamera);
                                GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                                isMoveOK = false;
                                Stopwatch sw = new Stopwatch();
                                sw.Restart();
                                while (true)
                                {
                                    Application.DoEvents();
                                    Thread.Sleep(2);
                                    if (visionProc.Result1 != null)
                                    {
                                        this.Invoke(new Action(()=>
                                        {
                                            temp_cailArr[i].pixX = Convert.ToSingle(visionProc.Result1.dColumn.ToString("F03"));
                                            temp_cailArr[i].pixY = Convert.ToSingle(visionProc.Result1.dRow.ToString("F03"));
                                            nud_plateX.Value = (decimal)Convert.ToSingle(visionProc.Result1.dColumn.ToString("F03"));
                                            nud_plateY.Value = (decimal)Convert.ToSingle(visionProc.Result1.dRow.ToString("F03"));

                                            HOperatorSet.GenCrossContourXld(out HObject crosing, visionProc.Result1.dRow, visionProc.Result1.dColumn, 200, visionProc.Result1.dAngle);
                                            DispObject(crosing, "red");

                                            isMoveOK = true;
                                            System.Threading.Thread.Sleep(300);
                                        }));
                                    }
                                    if (sw.ElapsedMilliseconds > 3000|| isMoveOK)
                                    {
                                        break;
                                    }
                                }
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                {
                                    if (!isMoveOK)
                                    {
                                        displalyInfo.displayErrorMain("拍照定位NG,退出标定");
                                    }
                                    break;
                                }
                            }

                            if (isMoveOK && !GlobalVar.isEstop && !GlobalVar.isExit)
                            {

                                CailPointToTable(temp_cailArr.ToList());

                                btn_calibrate_Click(btn_calibrate, null);

                            }
                        }
                        break;
                    case e_CameraPlate.定位相机平台2:
                        if (curVision.CailList != null && curVision.CailList.Count >= 9)
                        {
                            var temp_cailArr = curVision.CailList.ToArray();
                            var isMoveOK = false;
                            visionProc.curCameraPlate1 = curSelect;
                            isMoveOK = GlobalMotion.toPosition(-100, (int)e_card1_axis.贴标X1下, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                            for (int i = 0; i < temp_cailArr.Length; i++)
                            {
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realX, (int)e_card1_axis.贴标X2上, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realY, (int)e_card1_axis.贴标Y轴, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realR, (int)e_card1_axis.贴标R2上, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                visionProc.Result2 = null;
                                GlobalVar.e_Camera_Pos2 = e_Camera_Pos.未拍照;
                                Thread.Sleep(GlobalVar.userConfig.delayCamera);
                                GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                                isMoveOK = false;
                                Stopwatch sw = new Stopwatch();
                                sw.Restart();
                                while (true)
                                {
                                    Application.DoEvents();
                                    Thread.Sleep(2);
                                    this.Invoke(new Action(()=>
                                    {
                                        if (visionProc.Result2 != null)
                                        {
                                            temp_cailArr[i].pixX = Convert.ToSingle(visionProc.Result2.dColumn.ToString("F03"));
                                            temp_cailArr[i].pixY = Convert.ToSingle(visionProc.Result2.dRow.ToString("F03"));
                                            nud_plateX.Value = (decimal)Convert.ToSingle(visionProc.Result2.dColumn.ToString("F03"));
                                            nud_plateY.Value = (decimal)Convert.ToSingle(visionProc.Result2.dRow.ToString("F03"));

                                            isMoveOK = true;
                                            HObject crosing = new HObject();
                                            HOperatorSet.GenCrossContourXld(out crosing, visionProc.Result2.dRow, visionProc.Result2.dColumn, 200, visionProc.Result2.dAngle);
                                            DispObject(crosing, "red");
                                            System.Threading.Thread.Sleep(300);
                                        }
                                    }));
                                    
                                    if (sw.ElapsedMilliseconds > 3000|| isMoveOK)
                                    {
                                        break;
                                    }
                                }
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                {
                                    if (!isMoveOK)
                                    {
                                        this.Invoke(new Action(() =>
                                        {
                                            MessageBox.Show("拍照定位NG,退出标定");
                                        }));

                                        displalyInfo.displayInfoMain("拍照定位NG,退出标定");
                                    }
                                    break;
                                }
                            }

                            if (isMoveOK && !GlobalVar.isEstop && !GlobalVar.isExit)
                            {
                                CailPointToTable(temp_cailArr.ToList());

                                btn_calibrate_Click(btn_calibrate, null);

                            }
                        }
                        break;
                }

            }));
            ((Button)sender).Enabled = true;
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void btn_NG_conveyDistance_Click(object sender, EventArgs e)
        {
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.NG输送].ClearPos();
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.NG输送].PointMove((double)nud_NG_distance.Value, false);
        }

        private void btn_ConveryDistance_Click(object sender, EventArgs e)
        {
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.上层输送左].PointMove(-(double)nud_dis_ConveryReset.Value, false);
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.上层输送右].PointMove((double)nud_dis_ConveryReset.Value, false);
        }

        private void dgv_camera_calib_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Task.Run(new Action(()=>
            {
                try
                {
                    if (e.RowIndex < 0)
                        return;
                    double pixPosX = 0;
                    double pixPosY = 0;
                    double realX = 0;
                    double realY = 0;
                    double realR = 0;

                    if (e.ColumnIndex == 6)
                    {
                        try { double.TryParse(((DataGridViewTextBoxCell)dgv_camera_calib.Rows[e.RowIndex].Cells[1]).Value.ToString(), out pixPosX); }
                        catch { }
                        try { double.TryParse(((DataGridViewTextBoxCell)dgv_camera_calib.Rows[e.RowIndex].Cells[2]).Value.ToString(), out pixPosY); }
                        catch { }
                        try { double.TryParse(((DataGridViewTextBoxCell)dgv_camera_calib.Rows[e.RowIndex].Cells[3]).Value.ToString(), out realX); }
                        catch { }
                        try { double.TryParse(((DataGridViewTextBoxCell)dgv_camera_calib.Rows[e.RowIndex].Cells[4]).Value.ToString(), out realY); }
                        catch { }
                        try { double.TryParse(((DataGridViewTextBoxCell)dgv_camera_calib.Rows[e.RowIndex].Cells[5]).Value.ToString(), out realR); }
                        catch { }

                        GlobalMotion.Step_Labeling(e_Step_Label.吸标NG下压, e_platePro.双平台有, e_MachineStatus.无控制);
                        GlobalMotion.Step_Labeling(e_Step_Label.取标气缸抬起, e_platePro.双平台有, e_MachineStatus.无控制);
                        bool isMoveOK = GlobalMotion.toPosition((int)e_Card.Card1, (int)e_card1_axis.贴标Z轴, 0, 1, true);
                        if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                            return;
                        isMoveOK = GlobalMotion.toPosition((int)e_Card.Card1, (int)e_card1_axis.剔除Z轴, 0, 1, true);
                        if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                            return;

                        if (rbn_plate1.Checked)
                        {
                            isMoveOK = GlobalMotion.toPosition(-100, (int)e_card1_axis.贴标X2上, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;

                            isMoveOK = GlobalMotion.toPosition(realX, (int)e_card1_axis.贴标X1下, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                            isMoveOK = GlobalMotion.toPosition(realY, (int)e_card1_axis.贴标Y轴, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                            isMoveOK = GlobalMotion.toPosition(realR, (int)e_card1_axis.贴标R1下, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                        }
                        else
                        {
                            isMoveOK = GlobalMotion.toPosition(-100, (int)e_card1_axis.贴标X1下, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                            isMoveOK = GlobalMotion.toPosition(realX, (int)e_card1_axis.贴标X2上, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                            isMoveOK = GlobalMotion.toPosition(realY, (int)e_card1_axis.贴标Y轴, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                            isMoveOK = GlobalMotion.toPosition(realR, (int)e_card1_axis.贴标R2上, 1, true);
                            if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                return;
                        }
                        

                    }

                    if (e.ColumnIndex == 7)
                    {
                        double nCurX1 = GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标X1下].m_AxisSts.CurrPosi;
                        double nCurY1 = GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标Y轴].m_AxisSts.CurrPosi;
                        double nCurR1 = GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标R1下].m_AxisSts.CurrPosi;

                        double nCurX2 = GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标X2上].m_AxisSts.CurrPosi;
                        double nCurY2 = GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标Y轴].m_AxisSts.CurrPosi;
                        double nCurR2 = GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标R2上].m_AxisSts.CurrPosi;

                        if (GlobalMotion.TipInfo($"是否更新当前平台 轴坐标？")==1)
                        {
                            if (rbn_plate1.Checked)
                            {
                                dgv_camera_calib.Rows[e.RowIndex].Cells[3].Value = nCurX1;
                                dgv_camera_calib.Rows[e.RowIndex].Cells[4].Value = nCurY1;
                                dgv_camera_calib.Rows[e.RowIndex].Cells[5].Value = nCurR1;
                            }
                            else
                            {
                                dgv_camera_calib.Rows[e.RowIndex].Cells[3].Value = nCurX2;
                                dgv_camera_calib.Rows[e.RowIndex].Cells[4].Value = nCurY2;
                                dgv_camera_calib.Rows[e.RowIndex].Cells[5].Value = nCurR2;
                            }
                        }
                    }

                    if (e.ColumnIndex == 8)
                    {
                        if (GlobalMotion.TipInfo($"是否更新当前平台 像素坐标？") == 1)
                        {
                            if (nud_plateX.Value==0 || nud_plateY.Value==0)
                            {
                                MessageBox.Show("更新失败，请检测图像处理结果！");
                                return;
                            }
                            dgv_camera_calib.Rows[e.RowIndex].Cells[6].Value = nud_plateX.Value;
                            dgv_camera_calib.Rows[e.RowIndex].Cells[7].Value = nud_plateY.Value;
                        }
                    }
                }
                catch (Exception)
                {

                }
            }));
        }

        private void btn_snap_Click(object sender, EventArgs e)
        {
            var curSelect = GetCurrentSelet();
            nud_plateX.Value = 0;
            nud_plateY.Value = 0;
            switch (curSelect)
            {
                case e_CameraPlate.定位相机平台1:
                case e_CameraPlate.定位相机平台2:
                    {
                        visionProc.curCameraPlate1 = curSelect;
                        GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                    }
                    break;
                case e_CameraPlate.图案相机平台1:
                case e_CameraPlate.图案相机平台2:
                    {
                        visionProc.curCameraPlate2 = curSelect;
                        GlobalVar.cameraList[(int)e_Camera.图案相机].softTrigger();
                    }
                    break;
                case e_CameraPlate.检测相机平台1:
                case e_CameraPlate.检测相机平台2:
                    {
                        visionProc.curCameraPlate3 = curSelect;
                        GlobalVar.cameraList[(int)e_Camera.检测相机].softTrigger();
                    }
                    break;
            }
        }

        private e_CameraPlate GetCurrentSelet()
        {
            var e_cur = e_CameraPlate.定位相机平台1;
            if (rbn_ScanCamera.Checked)
            {
                if (rbn_plate1.Checked)
                    e_cur = e_CameraPlate.图案相机平台1;
                else if (rbn_plate2.Checked)
                    e_cur = e_CameraPlate.图案相机平台2;
            }
            else if (rbn_posCamera.Checked)
            {
                if (rbn_plate1.Checked)
                    e_cur = e_CameraPlate.定位相机平台1;
                else if (rbn_plate2.Checked)
                    e_cur = e_CameraPlate.定位相机平台2;
            }
            else if (rbn_CheckCamera.Checked)
            {
                if (rbn_plate1.Checked)
                    e_cur = e_CameraPlate.检测相机平台1;
                else if (rbn_plate2.Checked)
                    e_cur = e_CameraPlate.检测相机平台2;
            }
            return e_cur;
        }

        private void button45_Click(object sender, EventArgs e)
        {
            try
            {

                GlobalVar.e_Camera_Pos1 = e_Camera_Pos.未拍照;
                GlobalVar.e_Camera_Pos2 = e_Camera_Pos.未拍照;
                e_CameraPlate cameraPlate = e_CameraPlate.定位相机平台1;
                if (!rbn_plate1.Checked)
                {
                    cameraPlate = e_CameraPlate.定位相机平台2;
                }
                visionProc.curCameraPlate1 = cameraPlate;
                GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                Stopwatch sw = new Stopwatch();
                visionProc.Result1 = null;
                visionProc.Result2 = null;
                nud_plateX.Value = 0;
                nud_plateY.Value = 0;
                bool isok = false;

                sw.Restart();
                Task.Run(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(2);
                        this.Invoke(new Action(() =>
                        {
                            if (visionProc.Result1 != null && rbn_plate1.Checked)
                            {
                                nud_plateX.Value = (decimal)Convert.ToSingle(visionProc.Result1.dColumn.ToString("F03"));
                                nud_plateY.Value = (decimal)Convert.ToSingle(visionProc.Result1.dRow.ToString("F03"));
                                HObject crosing = new HObject();
                                HOperatorSet.GenCrossContourXld(out crosing, visionProc.Result1.dRow, visionProc.Result1.dColumn, 200, visionProc.Result1.dAngle);

                                DispObject(visionProc.ROI_List[(int)cameraPlate].ROI_Region, "red");
                                DispObject(crosing, "red");
                                isok = true;
                            }
                            if (visionProc.Result2 != null)
                            {
                                nud_plateX.Value = (decimal)Convert.ToSingle(visionProc.Result2.dColumn.ToString("F03"));
                                nud_plateY.Value = (decimal)Convert.ToSingle(visionProc.Result2.dRow.ToString("F03"));
                                HObject crosing = new HObject();
                                HOperatorSet.GenCrossContourXld(out crosing, visionProc.Result2.dRow, visionProc.Result2.dColumn, 200, visionProc.Result2.dAngle);
                                DispObject(visionProc.ROI_List[(int)cameraPlate].ROI_Region, "red");
                                DispObject(crosing, "red");
                                isok = true;
                            }
                        }));


                        if (sw.ElapsedMilliseconds > 3000 || isok)
                        {
                            break;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 20241202增加海康视觉标定
        /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>


        //左工位开始标定
        private void button46_Click(object sender, EventArgs e)
        {
            Task.Run(() => { Calibration_task1(); });
        }
        private void button49_Click(object sender, EventArgs e)
        {
            Task.Run(() => { Calibration_task2(); });
        }
        private void Calibration_task1()
        {
            var res = -1;

            try
            {
                //移动到起始位置及下相机拍照位置 绝对方式
                GlobalMotion.Step_Labeling(e_Step_Label.移至拍照位, e_platePro.平台1, e_MachineStatus.无控制);
                string Str = $"X1:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标X1下)} " +
                             $" ,Y:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴)}" +
                             $" ,Z:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴)} " +
                             $" ,R1:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标R1下)} ";
                displalyInfo.displayInfoMain($"位置：" + Str);

                //移位到第一个起点位置 相对方式
                if (GlobalMotion.Step_XYZR(0, 0, 0, 0) == -1)
                {
                    MessageBox.Show("轴位移失败，标定异常退出");
                    return;
                }
                Str = $"X1:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标X1下)} " +
                        $" ,Y:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴)}" +
                        $" ,Z:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴)} " +
                        $" ,R1:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标R1下)} ";
                displalyInfo.displayInfoMain($"位置：" + Str);

                //清楚上一次标定数据
                GlobalVar.VisionTcpIP.SendData("Clear1");
                Thread.Sleep(1500);

                double X = GlobalVar.userConfig.CalibrationXY;
                double Y = GlobalVar.userConfig.CalibrationXY;
                double A = GlobalVar.userConfig.CalibrationAngle;

                CalibrationBuf_XYZR NOW_XYZR = new CalibrationBuf_XYZR()
                {
                    X = GlobalMotion.GetCurrPosi(e_card1_axis.贴标X1下),
                    Y = GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴),
                    Z = GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴),
                    R = GlobalMotion.GetCurrPosi(e_card1_axis.贴标R1下)
                };


                //生产九点标定数据
                CalibrationBuf_XYZR[] calibrationBuf_XYZR = new CalibrationBuf_XYZR[12] {
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X + X, Y = NOW_XYZR.Y + Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - 0, Y = NOW_XYZR.Y + Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - X, Y = NOW_XYZR.Y + Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - X, Y = NOW_XYZR.Y - 0, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - 0, Y = NOW_XYZR.Y - 0, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X + X, Y = NOW_XYZR.Y - 0, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X + X, Y = NOW_XYZR.Y - Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - 0, Y = NOW_XYZR.Y - Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - X, Y = NOW_XYZR.Y - Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X, Y = NOW_XYZR.Y, Z = 0, R = NOW_XYZR.R + A },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X, Y = NOW_XYZR.Y, Z = 0, R = NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X, Y = NOW_XYZR.Y, Z = 0, R = NOW_XYZR.R - A }
                    };


                //标定
                for (int i = 0; i < 12; i++)
                {
                    if (GlobalMotion.Step_XYZR(calibrationBuf_XYZR[i].X, calibrationBuf_XYZR[i].Y, calibrationBuf_XYZR[i].Z, calibrationBuf_XYZR[i].R,true) == -1)
                    {
                        MessageBox.Show("轴位移失败，标定异常退出");
                        return;
                    }
                    Thread.Sleep(500);
                    Str = $"X1:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标X1下)} " +
                            $" ,Y:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴)}" +
                            $" ,Z:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴)} " +
                            $" ,R1:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标R1下)} ";
                    displalyInfo.displayInfoMain($"位置：" + Str);

                    string cmd = $"C01,{i},{calibrationBuf_XYZR[i].X},{ calibrationBuf_XYZR[i].Y},{calibrationBuf_XYZR[i].R}";
                    displalyInfo.displayInfoMain($"发送指令：" + cmd);
                    GlobalVar.VisionTcpIP.SendData(cmd);
                    Thread.Sleep(500);
                    GlobalVar.VisionTcpIP.GetData(out string command, out string mes);
                    if (command.Contains("NG"))
                    {
                        MessageBox.Show("视觉返回标定NG，标定异常退出");
                        return;
                    }
                    else if (command == string.Empty)
                    {
                        MessageBox.Show("视觉超时返回数据为空，标定异常退出");
                        return;
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        private void Calibration_task2()
        {
            var res = -1;

            try
            {
                //移动到起始位置及下相机拍照位置 绝对方式
                GlobalMotion.Step_Labeling(e_Step_Label.移至拍照位, e_platePro.平台2, e_MachineStatus.无控制);
                string Str = $"X2:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标X2上)} " +
                             $" ,Y:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴)}" +
                             $" ,Z:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴)} " +
                             $" ,R2:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标R2上)} ";
                displalyInfo.displayInfoMain($"位置：" + Str);

                //移位到第一个起点位置 相对方式
                if (GlobalMotion.Step_XYZR(0, 0, 0, 0) == -1)
                {
                    MessageBox.Show("轴位移失败，标定异常退出");
                    return;
                }
                Str = $"X2:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标X2上)} " +
                        $" ,Y:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴)}" +
                        $" ,Z:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴)} " +
                        $" ,R2:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标R2上)} ";
                displalyInfo.displayInfoMain($"位置：" + Str);

                //清楚上一次标定数据
                GlobalVar.VisionTcpIP.SendData("Clear3");
                Thread.Sleep(1500);

                double X = GlobalVar.userConfig.CalibrationXY;
                double Y = GlobalVar.userConfig.CalibrationXY;
                double A = GlobalVar.userConfig.CalibrationAngle;

                CalibrationBuf_XYZR NOW_XYZR = new CalibrationBuf_XYZR() { X = GlobalMotion.GetCurrPosi(e_card1_axis.贴标X2上),
                                                                           Y = GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴), 
                                                                           Z = GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴), 
                                                                           R = GlobalMotion.GetCurrPosi(e_card1_axis.贴标R2上)
                };

                //生产九点标定数据
                CalibrationBuf_XYZR[] calibrationBuf_XYZR = new CalibrationBuf_XYZR[12] {
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X + X, Y = NOW_XYZR.Y + Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - 0, Y = NOW_XYZR.Y + Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - X, Y = NOW_XYZR.Y + Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - X, Y = NOW_XYZR.Y - 0, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - 0, Y = NOW_XYZR.Y - 0, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X + X, Y = NOW_XYZR.Y - 0, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X + X, Y = NOW_XYZR.Y - Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - 0, Y = NOW_XYZR.Y - Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X - X, Y = NOW_XYZR.Y - Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X, Y = NOW_XYZR.Y, Z = 0, R = NOW_XYZR.R +A },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X, Y = NOW_XYZR.Y, Z = 0, R =  NOW_XYZR.R },
                    new CalibrationBuf_XYZR(){ X = NOW_XYZR.X, Y = NOW_XYZR.Y, Z = 0, R = NOW_XYZR.R-A }
                    };


                //标定
                for (int i = 0; i < 12; i++)
                {
                    if (GlobalMotion.Step_XYZR2(calibrationBuf_XYZR[i].X, calibrationBuf_XYZR[i].Y, calibrationBuf_XYZR[i].Z, calibrationBuf_XYZR[i].R, true) == -1)
                    {
                        MessageBox.Show("轴位移失败，标定异常退出");
                        return;
                    }
                    Thread.Sleep(500);
                    Str = $"X2:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标X2上)} " +
                            $" ,Y:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Y轴)}" +
                            $" ,Z:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标Z轴)} " +
                            $" ,R2:{GlobalMotion.GetCurrPosi(e_card1_axis.贴标R2上)} ";
                    displalyInfo.displayInfoMain($"位置：" + Str);

                    string cmd = $"C03,{i},{calibrationBuf_XYZR[i].X},{ calibrationBuf_XYZR[i].Y},{calibrationBuf_XYZR[i].R}";
                    displalyInfo.displayInfoMain($"发送指令：" + cmd);
                    GlobalVar.VisionTcpIP.SendData(cmd);
                    Thread.Sleep(500);
                    GlobalVar.VisionTcpIP.GetData(out string command, out string mes);
                    if (command.Contains("NG"))
                    {
                        MessageBox.Show("视觉返回标定NG，标定异常退出");
                        return;
                    }
                    else if (command == string.Empty)
                    {
                        MessageBox.Show("视觉超时返回数据为空，标定异常退出");
                        return;
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
        }


        //贴合位置1
        private void button50_Click(object sender, EventArgs e)
        {
            if (rest_out()!=1)
            {
                MessageBox.Show("取料或贴合气缸位未回到原位，安全隐患禁止运行；");
            } 
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照安全位X, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
            nres = GlobalMotion.Step_Labeling(e_Step_Label.移至OK位上方, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }

        //上相机位置1
        private void button51_Click(object sender, EventArgs e)
        {
            if (rest_out() != 1)
            {
                MessageBox.Show("取料或贴合气缸位未回到原位，安全隐患禁止运行；");
            }

            var nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照检测位,e_platePro.双平台无,e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }

            var angel = GlobalVar.motionConfig.Plate1_pos[(int)e_Pos.OK放标位].R;
            var angel2 = GlobalVar.motionConfig.Plate2_pos[(int)e_Pos.OK放标位].R;
            List<SigleAxis> posList = new List<SigleAxis>();
            posList.Add(new SigleAxis()
            {
                IsAbs = true,
                nAxis = (int)e_card1_axis.贴标R2上,
                pos = angel2,
                velrate = 1
            });
            posList.Add(new SigleAxis()
            {
                IsAbs = true,
                nAxis = (int)e_card1_axis.贴标R1下,
                pos = angel,
                velrate = 1
            });
            var bres = GlobalMotion.toPostionMutil(posList);
            if (!bres)
            {
                ;
            }

            nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照安全位X, e_platePro.双平台有, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }


        }

        //下相机位置1
        private void button60_Click(object sender, EventArgs e)
        {
            if (rest_out() != 1)
            {
                MessageBox.Show("取料或贴合气缸位未回到原位，安全隐患禁止运行；");
            }
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照安全位X, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
            nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照位, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }

        //贴合位置2
        private void button61_Click(object sender, EventArgs e)
        {
            if (rest_out() != 1)
            {
                MessageBox.Show("取料或贴合气缸位未回到原位，安全隐患禁止运行；");
            }
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照安全位X, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
            nres = GlobalMotion.Step_Labeling(e_Step_Label.移至OK位上方, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }
         //上相机位置2
        private void button55_Click(object sender, EventArgs e)
        {
            if (rest_out() != 1)
            {
                MessageBox.Show("取料或贴合气缸位未回到原位，安全隐患禁止运行；");
            }
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照检测位);
            if (nres != 1)
            {
                ;
            }

            var angel = GlobalVar.motionConfig.Plate1_pos[(int)e_Pos.OK放标位].R;
            var angel2 = GlobalVar.motionConfig.Plate2_pos[(int)e_Pos.OK放标位].R;
            List<SigleAxis> posList = new List<SigleAxis>();
            posList.Add(new SigleAxis()
            {
                IsAbs = true,
                nAxis = (int)e_card1_axis.贴标R2上,
                pos = angel2,
                velrate = 1
            });
            posList.Add(new SigleAxis()
            {
                IsAbs = true,
                nAxis = (int)e_card1_axis.贴标R1下,
                pos = angel,
                velrate = 1
            });
            var bres = GlobalMotion.toPostionMutil(posList);
            if (!bres)
            {
                ;
            }

            nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照安全位X, e_platePro.双平台有, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }
        //下相机位置2
        private void button54_Click(object sender, EventArgs e)
        {
            if (rest_out() != 1)
            {
                MessageBox.Show("取料或贴合气缸位未回到原位，安全隐患禁止运行；");
            }
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照安全位X, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
            nres = GlobalMotion.Step_Labeling(e_Step_Label.移至拍照位, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }

        //OK位置向下
        private void button52_Click(object sender, EventArgs e)
        {
            ;
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.OK位向下移动,e_platePro.平台1, e_MachineStatus.手动界面);
            if (nres != 1)
            {
                ;
            }
        }

        //气缸下压1
        private void button62_Click(object sender, EventArgs e)
        {
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.取标气缸下压, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }
        //气缸抬起1
        private void button64_Click(object sender, EventArgs e)
        {
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.取标气缸抬起, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }

        bool stateA = false;
        //真空打开/关闭
        private void button63_Click(object sender, EventArgs e)
        {

            if (GlobalMotion.Output_CardEx2[(ushort)e_output_extCard2.吸标靶面吸气1])
            {
                stateA = false;
                button63.Text = "真空OFF";
            }
            else
            {
                stateA = true;
                button63.Text = "真空ON";
            }

            GlobalMotion.CardExt_2.setOut((ushort)e_output_extCard2.吸标靶面吸气1, (stateA ? e_out_OnOff.off : e_out_OnOff.on));//信号取反

        }
        //OK位置向下2
        private void button53_Click(object sender, EventArgs e)
        {
            ;
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.OK位向下移动, e_platePro.平台2, e_MachineStatus.手动界面);
            if (nres != 1)
            {
                ;
            }
        }
        //气缸下压2
        private void button67_Click(object sender, EventArgs e)
        {
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.取标气缸下压, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }
        //气缸抬起2
        private void button65_Click(object sender, EventArgs e)
        {
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.取标气缸抬起, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                ;
            }
        }

        bool stateB = false;
        //真空打开/关闭2
        private void button66_Click(object sender, EventArgs e)
        {

            if (GlobalMotion.Output_CardEx2[(ushort)e_output_extCard2.吸标靶面吸气2])
            {
                stateB = false;
                button66.Text = "真空OFF";
            }
            else
            {
                stateB = true;
                button66.Text = "真空ON";
            }

            GlobalMotion.CardExt_2.setOut((ushort)e_output_extCard2.吸标靶面吸气2, (stateB ? e_out_OnOff.off : e_out_OnOff.on));//信号取反
        }

        //取料/贴合气缸复位
        private int rest_out()
        {
            var nres = GlobalMotion.Step_Labeling(e_Step_Label.取标气缸抬起, e_platePro.平台1, e_MachineStatus.无控制);
            if (nres != 1)
            {
                return -1;
            }
            nres = GlobalMotion.Step_Labeling(e_Step_Label.取标气缸抬起, e_platePro.平台2, e_MachineStatus.无控制);
            if (nres != 1)
            {
                return -1;
            }
            return 1;
        }

        //上相机拍照关联1
        private void button58_Click(object sender, EventArgs e)
        {
            string cmd = $"C04";
            displalyInfo.displayInfoMain($"发送指令：" + cmd);
            GlobalVar.VisionTcpIP.SendData(cmd);
            Thread.Sleep(500);
            GlobalVar.VisionTcpIP.GetData(out string command, out string mes);
            if (command.Contains("OK"))
            {
                MessageBox.Show("视觉返回OK，发送指令：" + command);

            }
            else if(command.Contains("NG"))
            {
                MessageBox.Show("视觉返回NG，发送指令：" + command);

            }
            else if (command == string.Empty)
            {
                MessageBox.Show("视觉超时返回数据为空，发送指令：" + command);

            }
        }
        //下相机拍照关联1
        private void button56_Click(object sender, EventArgs e)
        {
            string cmd = $"C05";
            displalyInfo.displayInfoMain($"发送指令：" + cmd);
            GlobalVar.VisionTcpIP.SendData(cmd);
            Thread.Sleep(500);
            GlobalVar.VisionTcpIP.GetData(out string command, out string mes);
            if (command.Contains("OK"))
            {
                MessageBox.Show("视觉返回OK，发送指令：" + command);

            }
            else if (command.Contains("NG"))
            {
                MessageBox.Show("视觉返回NG，发送指令：" + command);

            }
            else if (command == string.Empty)
            {
                MessageBox.Show("视觉超时返回数据为空，发送指令：" + command);

            }
        }
        //上相机拍照关联2
        private void button59_Click(object sender, EventArgs e)
        {
            string cmd = $"C06";
            displalyInfo.displayInfoMain($"发送指令：" + cmd);
            GlobalVar.VisionTcpIP.SendData(cmd);
            Thread.Sleep(500);
            GlobalVar.VisionTcpIP.GetData(out string command, out string mes);
            if (command.Contains("OK"))
            {
                MessageBox.Show("视觉返回OK，发送指令：" + command);

            }
            else if (command.Contains("NG"))
            {
                MessageBox.Show("视觉返回NG，发送指令：" + command);

            }
            else if (command == string.Empty)
            {
                MessageBox.Show("视觉超时返回数据为空，发送指令：" + command);

            }
        }

        //下相机拍照关联3
        private void button57_Click(object sender, EventArgs e)
        {
            string cmd = $"C07";
            displalyInfo.displayInfoMain($"发送指令：" + cmd);
            GlobalVar.VisionTcpIP.SendData(cmd);
            Thread.Sleep(500);
            GlobalVar.VisionTcpIP.GetData(out string command, out string mes);
            if (command.Contains("OK"))
            {
                MessageBox.Show("视觉返回OK，发送指令：" + command);

            }
            else if (command.Contains("NG"))
            {
                MessageBox.Show("视觉返回NG，发送指令：" + command);

            }
            else if (command == string.Empty)
            {
                MessageBox.Show("视觉超时返回数据为空，发送指令：" + command);

            }
        }


    }


    public class CalibrationBuf_XYZR
    {
        public double X;
        public double Y;
        public double Z;
        public double R;
    }
}
